<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>

<html>
	<head>
		<%@ include file="/WEB-INF/views/include/common.jsp" %>
		<meta name="AUTHOR" content="QroTech Inc." />
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="CACHE-CONTROL" content="NO-CACHE"/>
		<meta http-equiv="PRAGMA" content="NO-CACHE"/>
		<meta name="ROBOTS" content="NOINDEX, NOFOLLOW"/>
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<title>큐로넷::위치관제서비스</title>
		<link rel="stylesheet" href="${cssUrl}/bigPopUp.css" type="text/css" />
		<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
		<!-- <script src="http://code.jquery.com/jquery-1.9.1.js"></script>-->
  		<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
		
		<style>
		.ui-datepicker{ font-size: 12px; width: 280px; }
		#map_canvas { height: 80% }
		</style>
		<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCjYzALnSN1zEr2CcvzGGwFxBylVDpFcCI&sensor=false"></script>
		<title>목적지 관리</title>
	</head>
	<body onload="initialize()">
		<div class="wrapper">
			<div class="popup_box">
				<div class="popup_content">
					<div class="popup_title_box" >
						<div class="destination_title">목적지 관리</div>
						<div class="close_button"><img src="${imgUrl}/close.png" onClick="javascript:self.close()"></div>
					</div>
					<div class="calendar_box">
						<div class="carInfo_date">
							<div class="carInfo"><span id="carInfo"></span></div>
							<div class="date"><span class=>날짜 :</span> <span id="todayDate"></span></div>
						</div>
						<div class="calendar_destinationTable">
							<div class="calendar">
								<div id="datepicker"></div>
							</div>
							<div class="destination_Table">
								
									<div class="table_box">
										<div class="table_head">
											<table cellpadding="0" cellspacing="0">
											
												<tr >
													<th width="75px">예정시각</th>
													<th width="75px">목적지명</th>
													<th width="75px">반복</th>
													<th width="170px">위치</th>
													<th width="75px">통과시각</th>
													<th width="*">관리</th>
												</tr>
										</table>
									</div>
									<div class="table_body">
										<table cellpadding="0" cellspacing="0" id="destinationList">
											<tr onClick="setData(this)">
												<td width="75px" id="arriDate"></td>
												<td width="75px" id="name"></td>
												<td width="75px" id="checkTypeStr"></td>
												<td width="170px" id="address"> </td>
												<td width="75px" id="passedDate"></td>
												<td width="*" class="button_delete"><a id="deleteButton" onClick="updateDel(this)">삭제</a>
												  									<input type="hidden" id="destinationCode"/> 
												  									<input type="hidden" id="checkType"/>
												  									<input type="hidden" id="arrivalDay"/>
												  									<input type="hidden" id="arrivalWeek"/>
												  									</td>
											</tr>
											<!-- <tr>
												<td width="75px">12:00</td>
												<td width="75px">목적지명</td>
												<td width="75px">매주:월화수목금토일</td>
												<td width="170px">경기도 </td>
												<td width="75px">통과시각</td>
												<td width="*" class="button_delete"><a >삭제</a>  </td>
											</tr>
											<tr>
												<td width="75px">12:00</td>
												<td width="75px">목적지명</td>
												<td width="75px">매월:10일</td>
												<td width="170px">경기도 </td>
												<td width="75px">통과시각</td>
												<td width="*" class="button_delete"><a >삭제</a>  </td>
											</tr>
											<tr>
												<td width="75px">12:00</td>
												<td width="75px">목적지명</td>
												<td width="75px">한번만</td>
												<td width="170px">경기도 </td>
												<td width="75px">통과시각</td>
												<td width="*" class="button_delete"><a >삭제</a>  </td>
											</tr>
											<tr>
												<td width="75px">12:00</td>
												<td width="75px">목적지명</td>
												<td width="75px">매주:월수금</td>
												<td width="170px">경기도 </td>
												<td width="75px">통과시각</td>
												<td width="*" class="button_delete"><a >삭제</a>  </td>
											</tr>
											<tr>
												<td width="75px">12:00</td>
												<td width="75px">목적지명</td>
												<td width="75px">매월:말일</td>
												<td width="170px">경기도 </td>
												<td width="75px">통과시각</td>
												<td width="*" class="button_delete"><a >삭제</a>  </td>
											</tr>
											<tr>
												<td width="75px">12:00</td>
												<td width="75px">목적지명</td>
												<td width="75px">매주:화목</td>
												<td width="170px">경기도 </td>
												<td width="75px">통과시각</td>
												<td width="*" class="button_delete"><a >삭제</a>  </td>
											</tr> -->
											
											
											
											
										</table>
									</div><!--table_body-->
								</div><!--table_box-->
							</div><!--destination_Table-->
						</div><!--calendar_destinationTable-->
					</div><!--calendar_box-->
					<div class="map_box">
						<div class="display_destination">
							<div class="display_table">
								<form id="destinationInfo">
									<input type="hidden" name="destinationCode" id="inputDestinationCode" />
									<input type="hidden" name="inputCheckType" id="inputCheckType" />
									<input type="hidden" name="carCode" id="inputCarCode" />
								<table class="outerTable" cellpadding="0" cellspacing="0">
								<tr>
									<th>목적지명</th>
									<td class="td1"><span><input id="inputName" name="name" type="text" size="30"></span></td>
								</tr>
								<tr>
									<th>예정시각</th>
									<td class="td2"><span>
										<select name="hour" id="inputArriDateHour">
										<c:forEach var="i" begin="0" end="23">
											<option value="<fmt:formatNumber value="${i}" pattern="00"/>"><fmt:formatNumber value="${i}" pattern="00"/></option>
										</c:forEach>
										</select>시
										<select name="minute" id="inputArriDateMinute">
											<c:forEach var="i" begin="0" end="59">
												<option value="<fmt:formatNumber value="${i}" pattern="00"/>"><fmt:formatNumber value="${i}" pattern="00"/> </option>
											</c:forEach>
										</select>분</span>										
									</td>
								</tr>
								<tr>
									<th>위치</th>
									<td class="td3"><span><input type="text" id="inputAddress" name="address" size="40">
										<a onClick="changeAddress()" style="cursor:pointer;">▶</a></span>
										<p>지도를 클릭하면 목적지 위치를 바로 등록할 수 있습니다.</p>
										<input type="hidden" id="lat" name="lat"/>
										<input type="hidden" id="lng" name="lng"/>
										
										</td>
								</tr>
								<tr>
									<th>반복</th>
									<td class="td4">
										<div class="period">
											<div class="oneTime">
												<label >한번만</label><input type="radio" name="checkType" checked="checked" value="0">
											</div>
											<div class="week">
												<div class="label" ><label>매주</label><input name="checkType" type="radio" value="1"></div>
													<div class="days">
														<table cellpadding="0" cellspacing="0">
															<tr>
																<td>월</td><td>화 </td><td>수</td><td>목</td><td>금</td><td>토</td><td>일</td>
																		      
															</tr>
															<tr>
																<td><input name="tempArrivalWeek" value="1" type="checkbox"></td><td><input name="tempArrivalWeek" value="2" type="checkbox"></td><td><input name="tempArrivalWeek" value="3" type="checkbox"></td><td><input name="tempArrivalWeek" value="4" type="checkbox"></td><td><input name="tempArrivalWeek" value="5" type="checkbox"></td><td><input name="tempArrivalWeek" value="6" type="checkbox"></td><td><input name="tempArrivalWeek" value="0" type="checkbox"></td>
															</tr>
																	
														</table>
													</div>
											</div>
											<div class="month">
												<div class="label" ><label>매월</label><input name="checkType" type="radio" value="2"></div>
												<select name="arrivalDay" id="arrivalDay">
													<c:forEach var="i" begin="1" end="31">
														<option value="${i}"><fmt:formatNumber value="${i}" pattern="00"/>일</option>
													</c:forEach>
													<option value="32">말일</option>
												</select>
											</div>
												
													
													
										</div><!--period-->
									</td>
								</tr>
							</table>
							</form>
						</div>
							
							<div class="buttons">
									<a id="updateButton" onClick="updateDestination()">수정</a>
									<a id="registButton" onClick="regDestination()">새목적지로 등록</a>
									<!--<a class="margin_zero">자주쓰는 목적지로 등록</a>-->
									
								</div>
							
						</div><!--display_destination-->
						<div  id="map_canvas" style="width:415px;height:325px;">
						
					</div><!--map_box-->
				</div><!--popup_content-->
				
				
			</div><!--popup_box-->
		</div><!--wrapper-->		
		<script>
			var _this = this;
			
			$(function() {
				init();
			    $( "#datepicker" ).datepicker({ 
			    	autoSize: true,
			    	dateFormat : 'yy-mm-dd',			    	
			    	onSelect : function(selectedDate) {
			    		getDestinationList(selectedDate);
			    		
			    		//선택된 날이 오늘 이후이면 삭제, 수정, 새목적지 등록 disable
			    		if (selectedDate < formatter.dateFormatYYYYMMDD(new Date())) {
			    			$('#updateButton').removeAttr("onClick").css("background-color","grey");
			    			$('#destinationList tr').each(function(){
			    				$(this).find('#deleteButton').removeAttr("onclick").css("background-color","grey");
			    			});
			    		} else {
			    			$('#updateButton').attr("onClick", "updateDestination()").css("background-color","#365789");
			    			$('#destinationList tr').each(function(){
			    				$(this).find('#deleteButton').attr("onclick", "updateDel(this)").css("background-color","#365789");
			    			});
			    		}
			    	}
			    });
			  });
			function init(){
				
				$('#inputCarCode').val($('#carCode', opener.document.theForm).val());
				// 시간 설정
				var nowDate = new Date();
				$("#inputArriDateHour").val(formatter.twoDigits(nowDate.getHours())).attr("selected", "selected");
				$("#inputArriDateMinute").val(formatter.twoDigits(nowDate.getMinutes())).attr("selected", "selected");
				
				getDestinationList();
				getCarInfo();
			}
			function getDestinationList(selectedDate) {
				_this.table1 = tableSync('destinationList');
				
				var date = formatter.dateFormatYYYYMMDD(new Date());
				var fullDate = formatter.dateFormatYYYYMMDD(new Date()) + " 23:59:59";
				var carCode = $('#inputCarCode').val();
				if (selectedDate != null && selectedDate != '') {
					date = selectedDate;
					fullDate = selectedDate + " 23:59:59";
				} 
				var whereQuery = 0;
				if (date >= formatter.dateFormatYYYYMMDD(new Date())) {
					whereQuery = 1;
				}
				//상위 날짜 셋팅
				$('#todayDate').text(date);
				var param = "date="+date+"&fullDate="+fullDate+"&carCode="+carCode+"&whereQuery="+whereQuery;
				var url="/map/getDestinationList.json";
				
				AjaxPost(url, param, function(data){
					if (data.destinationList.length == 0) {
						return;
					}
					$(data.destinationList).each(function(ind) {
						var checkType = this['checkType'];
						var arrivalWeek = "";
						var str = "";
						
						if (checkType == 0) {
							this['checkTypeStr'] = "한번만";
						}else if(checkType == 1) {
							arrivalWeek = this['arrivalWeek'];
							
							if (arrivalWeek.indexOf("1") != -1) {
								str += "월";
							} 
							if (arrivalWeek.indexOf("2") != -1) {
								str += "화";
							} 
							if (arrivalWeek.indexOf("3") != -1) {
								str += "수";
							} 
							if (arrivalWeek.indexOf("4") != -1) {
								str += "목";
							} 
							if (arrivalWeek.indexOf("5") != -1) {
								str += "금";
							} 
							if (arrivalWeek.indexOf("6") != -1) {
								str += "토";
							}
							if (arrivalWeek.indexOf("0") != -1) {
								str += "일";
							} 
							this['checkTypeStr'] = "매주:"+str;
						}else{
							if(this['arrivalDay'] == 32) {
								this['checkTypeStr'] = "매월:말일";	
							} else {
								this['checkTypeStr'] = "매월:"+this['arrivalDay']+"일";
							}
						}
					});
					_this.table1.tableAutoSync(data.destinationList);
				});
			}
			function setData(tr) {
				$("#inputArriDateHour").val($(tr).find('#arriDate').text().split(":")[0]).attr("selected", "selected");
				$("#inputArriDateMinute").val($(tr).find('#arriDate').text().split(":")[1]).attr("selected", "selected");
				//목적지명
				$('#inputName').val($(tr).find('#name').text());
				$('#inputAddress').val($(tr).find('#address').text());
				$('#inputDestinationCode').val($(tr).find('#destinationCode').val());
				$('#inputCheckType').val($(tr).find('#checkType').val());
				
				var checkType = $(tr).find('#checkType').val();
				var arrivalWeek = $(tr).find('#arrivalWeek').val();
				var arrivalDay = $(tr).find('#arrivalDay').val();
				//반복 리셋
				dataReset();
				$("input[name='checkType']").filter('input[value='+checkType+']').prop("checked", "checked");
				 var str = "";
				 if (checkType == 1){
					for(var i = 0; i < arrivalWeek.length; i++) {
						str = arrivalWeek.charAt(i);
						
						$("input[name=tempArrivalWeek]").each(function() {
							if($(this).val() == str) {
								$(this).prop('checked', 'checked');
							}
						});
					}
				} else if (checkType == 2){
					$('#arrivalDay option[value="'+arrivalDay+'"]').prop('selected', true);
				}  
				gMapCodeAddress($(tr).find('#address').text());
				
			}
			
			function dataReset() {
				$('input[name="checkType"]').each(function() {
					$(this).attr('checked', false);
				});
				$('input[name="tempArrivalWeek"]').each(function() {
					$(this).attr('checked', false);
				});
				$('#arrivalDay option[value="1"]').prop('selected', true);
			}
			function updateDel(td){
				$('#inputDestinationCode').val($(td).parent().find('#destinationCode').val());
				$('#inputCheckType').val($(td).parent().find('#checkType').val());
				var param = $('#destinationInfo').serialize();
				var url = "updateDestination.json";
				AjaxPost(url, param, function(data){
					alert(data.msg);
					getDestinationList($('#todayDate').text());
				});
			}
			
			function updateDestination() {
				/* var nowDate = $('#todayDate').text();
				var nowHour = $("select[name=hour]").val();
				var nowMinute = $("select[name=minute]").val();
				
				var arrivalDate = nowDate.split("-").join("")+nowHour+nowMinute+"00";
				var param = $('#destinationInfo').serialize()+"&arriDate="+arrivalDate; */
				var param = $('#destinationInfo').serialize();
				
				var destinationCode = $('#inputDestinationCode').val();
				var carCode = $('#inputCarCode').val();
				
				if (destinationCode == '' || carCode == '') {
					alert('목적지를 등록하세요.');
					return;
				}
				var url = "updateDestination.json";
				AjaxPost(url, param, function(data){
					regDestination();
				});
				
			}
			function regDestination() {
				var name = $('#inputName').val();
				if(name == '') {
					return;
				}		
			    var str = "";  
			    $("input[name=tempArrivalWeek]:checkbox:checked").each(function (index) {  
			       str += $(this).val();  
			    });  
				if (str == "") {
					str = "0";	
				}
				$('#checkType').val($(":input:radio[name=checkType]:checked").val());
				var nowDate = $('#todayDate').text();
				var nowHour = $("select[name=hour]").val();
				var nowMinute = $("select[name=minute]").val();
				
				var arrivalDate = nowDate.split("-").join("")+nowHour+nowMinute+"00";
				var param = $('#destinationInfo').serialize()+"&arriDate="+arrivalDate+"&arrivalWeek="+str;
				var url = "regDestination.json";
				AjaxPost(url, param, function(data){
					alert(data.msg);
					getDestinationList($('#todayDate').text());
					//document.location.reload();
				});
			}
			function changeAddress() {
				gMapCodeAddress($('#inputAddress').val());
			}
			
			function getCarInfo() {
				/* 서울05가1234  |  홍길동  |  큐로테크 영업부 */
				var carCode = $('#inputCarCode').val();
				var param = "carCode="+carCode;
				var url="/map/getCarInfo.json";
				
				AjaxPost(url, param, function(data){
					jsonLog(data.carInfo);
					var regiNumber = data.carInfo['carRegiNumber'];
					var dri_name = data.carInfo['dri_Name'];
					var deptName = data.carInfo['dep_DeptName'];
					
					$('#carInfo').text(regiNumber+"  |  "+dri_name+"  |  "+deptName);
				});
			}
			var map;
	        var selectedMarker;
	      function initialize() {
	        var mapOptions = {
	          center: new google.maps.LatLng(37.565262680889965, 126.97311401367188),
	          zoom: 10,
	          minZoom : 3,
	          maxZoom : 17,
	          mapTypeId: google.maps.MapTypeId.ROADMAP
	        };
	        map = new google.maps.Map(document.getElementById("map_canvas"),
	            mapOptions);
	        
	        initBinding();
	      }
	      
	      function initBinding(){
	    	  
	    	  $('#move1').bind('click', function(){
	    		  move1();
	    	  });
	    	  
	    	 /*  $('#zoom3').bind('click', function(){
	  				gMapChangeZoom(13);
	    	  }); */
	    	  
			  $('#gotoAddressPosition').bind('click', function(){
				  gMapCodeAddress($('#setAddress').val());
			  });
	    	  
	    	  
	    	  google.maps.event.addListener(map, 'click', function(event) {
	    		    //map.setZoom(10);
	    		    gMapShowClickedPosition(event.latLng);
	    		  });
	      }
	      var infowindow = new google.maps.InfoWindow();
	      var geocoder = new google.maps.Geocoder();
	      
	      // 클릭된 곳에 마크와 주소 표시
	      function gMapShowClickedPosition(latLng){
	    	  
	    	  
	    	  if(selectedMarker != null){
	    		  selectedMarker.setMap(null);
	        	  infowindow.open(null, null);  
	    	  }
	    	  var address="";
	    	  geocoder.geocode({'latLng': latLng}, function(results, status) {
	    	      if (status == google.maps.GeocoderStatus.OK) {
	    	        if (results[0]) {
//	     	          map.setZoom(11);
	    	          selectedMarker = new google.maps.Marker({
	    	              position: latLng,
	    	              map: map
	    	          });
	    	          address=results[0].formatted_address;
	    	          infowindow.setContent(address.replace("대한민국", ""));
	    	          infowindow.open(map, selectedMarker);
	    	          
	    	          gMapSetAddress(address);// ajax 통신이기 때문에 이 곳에서 해야 한다.
	    	          gMapSetLatLng(latLng);
	    	        }
	    	      } else {
	    	        alert("Geocoder failed due to: " + status);
	    	      }
	    	    });
	    	  
	      }
	      
	      
	      // 입력된 주소로 이동
	      function gMapCodeAddress(address) {

	    	  
	    	  if(selectedMarker != null){
	    		  selectedMarker.setMap(null);
	        	  infowindow.open(null, null);  
	    	  }
	    	    geocoder.geocode( { 'address': address}, function(results, status) {
	    	      if (status == google.maps.GeocoderStatus.OK) {
	    	        map.setCenter(results[0].geometry.location);
	    	        gMapShowClickedPosition(results[0].geometry.location);
	    	      } else {
	    	        alert("Geocode was not successful for the following reason: " + status);
	    	      }
	    	    });
	    	  }
	      
	      // 주소 넣기.
	      function gMapSetAddress(address){
	    	  address = address.replace("대한민국","");
	    	  $('#inputAddress').val(address);
	      }
	      
	      // 위경도 넣기.
	      function gMapSetLatLng(latLng){
	    	  $('#lat').val(latLng.lat());
	    	  $('#lng').val(latLng.lng());
	      }
	      function move1(){
	    	  gMapGotoPosition(37.397866,126.846443);
	      }
	      
	      // 지도 위치 이동하기.
	      function gMapGotoPosition(lat, lng){
	    	  var pos = new google.maps.LatLng(lat,lng);
				map.setCenter(pos);
	      }
	      
	      //지도 줌 변경
	      function gMapChangeZoom(zoom){
	    	  map.setZoom(zoom);
	      }
	      
		</script>
	</body>
</html>

